"""
Bios api
"""


import json

from .command import raw_command
from .argument import build_args
from .power import restart
from redfishtoollib import main


# get bios properties
# response: json string
# [{key: 'xxx', value: 'xxx'},{'key': 'xxx', value: 'xxx'}]
def get_bios():
    args = build_args()
    cmd = raw_command(args, 'GET', '/redfish/v1/Systems', None)
    res = main(cmd)
    try:
        urls = json.loads(res)
    except ValueError:
        urls = {}
    if len(urls.get('Members', [])) > 0:
        base_url = urls.get('Members', [])[0].get('@odata.id')
        cmd = raw_command(args, 'GET', base_url + '/Bios', None)
        res = main(cmd)
        try:
            attrs = json.loads(res)
        except ValueError:
            attrs = {}
        attrs = attrs['Attributes']
        ret = list(map(lambda x: {'key': x, 'value': attrs[x]}, attrs.keys()))
        print(json.dumps(ret, indent=4))


# set bios properties
# params: json string
# format: "{\"Attributes\": {\"key\": \"value\"}, {\"key\": \"value\"}}"
def set_bios():
    args = build_args()
    cmd = raw_command(args, 'GET', '/redfish/v1/Systems', None)
    res = main(cmd)
    try:
        urls = json.loads(res)
    except ValueError:
        urls = {}
    if len(urls.get('Members', [])) > 0:
        base_url = urls.get('Members', [])[0].get('@odata.id')
        cmd = raw_command(args, 'GET', base_url + '/Bios', None)
        res = main(cmd)
        try:
            attrs = json.loads(res)
        except ValueError:
            attrs = {}
        setting_url = attrs.get('@Redfish.Settings', {}).get('SettingsObject', {}).get('@odata.id')
        if setting_url:
            cmd = raw_command(args, 'PATCH', setting_url, args.d)
            main(cmd)
            restart()


# search bios property
# params: property name
def find_bios():
    args = build_args()
    cmd = raw_command(args, 'GET', '/redfish/v1/Systems', None)
    res = main(cmd)
    try:
        urls = json.loads(res)
    except ValueError:
        urls = {}
    if len(urls.get('Members', [])) > 0:
        base_url = urls.get('Members', [])[0].get('@odata.id')
        cmd = raw_command(args, 'GET', base_url + '/Bios', None)
        res = main(cmd)
        try:
            attrs = json.loads(res)
        except ValueError:
            attrs = {}
        attrs = attrs['Attributes']
        print(json.dumps({
            'key': args.d,
            'value': attrs[args.d]
        }, indent=4))


# reset all bios properties
def reset_bios():
    print('Cannot be reset')

